package com.example.healthcondition.services.impl;

import com.example.healthcondition.entity.ExerciseSuggestions;
import com.example.healthcondition.entity.HealthData;
import com.example.healthcondition.mapper.ExerciseSuggestionsMapper;
import com.example.healthcondition.mapper.HealthDataMapper;
import com.example.healthcondition.services.ExerciseSuggestionsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Service
public class ExerciseSuggestionsServiceImpl implements ExerciseSuggestionsService {

    @Autowired
    private HealthDataMapper healthDataMapper;

    @Autowired
    private ExerciseSuggestionsMapper exerciseSuggestionsMapper;

    @Override
    public ExerciseSuggestions generateExerciseSuggestions(Integer userId) {
        // 获取用户最新的健康数据
        HealthData healthData = healthDataMapper.findLatestByUserId(userId);
        if (healthData == null) {
            throw new RuntimeException("未找到用户的健康数据");
        }

        // 计算 BMI
        BigDecimal bmi = calculateBMI(healthData.getWeight(), healthData.getHeight());

        // 根据 BMI 和年龄生成运动建议
        String suggestionType;
        String description;
        if (healthData.getAge() > 60) {
            suggestionType = "walk";
            description = "建议走路 " + calculateWalkTime(bmi) + " 分钟";
        } else {
            suggestionType = "run";
            description = "建议跑步 " + calculateRunTime(bmi) + " 分钟";
        }

        // 创建运动建议
        ExerciseSuggestions exerciseSuggestions = new ExerciseSuggestions();
        exerciseSuggestions.setUserId(userId);
        exerciseSuggestions.setSuggestionType(suggestionType);
        exerciseSuggestions.setDescription(description);
        exerciseSuggestions.setCreatedAt(LocalDateTime.now());

        // 保存运动建议
        exerciseSuggestionsMapper.insertExerciseSuggestions(exerciseSuggestions);
        return exerciseSuggestions;
    }

    private BigDecimal calculateBMI(BigDecimal weight, BigDecimal height) {
        if (weight == null || height == null || height.compareTo(BigDecimal.ZERO) == 0) {
            return null;
        }
        return weight.divide(height.pow(2), 2, BigDecimal.ROUND_HALF_UP);
    }

    private int calculateRunTime(BigDecimal bmi) {
        if (bmi.compareTo(new BigDecimal("25")) > 0) { // BMI > 25，超重
            return 60; // 跑步 60 分钟
        } else if (bmi.compareTo(new BigDecimal("18.5")) < 0) { // BMI < 18.5，体重不足
            return 30; // 跑步 30 分钟
        } else {
            return 45; // 跑步 45 分钟
        }
    }

    private int calculateWalkTime(BigDecimal bmi) {
        if (bmi.compareTo(new BigDecimal("25")) > 0) { // BMI > 25，超重
            return 90; // 走路 90 分钟
        } else if (bmi.compareTo(new BigDecimal("18.5")) < 0) { // BMI < 18.5，体重不足
            return 45; // 走路 45 分钟
        } else {
            return 60; // 走路 60 分钟
        }
    }
}
